package com.nan.leetcode.剑指offer第二版.在排序数组中查找数字i;

public class Test {
    //使用二分查找做
    public int search(int[] nums, int target) {
        int x=0;
        int left=0;
        int right= nums.length-1;
        while(right>=left) {
            int m=(left+right)/2;
            if (nums[m]<target) {
                left=m+1;
            }else if(nums[m]>target){
                right=m-1;
            }else if(nums[m]==target){
                for(int i=m;i>=0;i--){
                    if(nums[i]==target){
                        x++;
                    }else{
                        break;
                    }
                }
                for(int y=m+1;y<nums.length;y++){
                    if(nums[y]==target){
                        x++;
                    }else{
                        break;
                    }
                }
                return x;
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        int[] nums=new int[]{5,7,7,7,8};
        int target=6;
        Test test=new Test();
        int x=test.search(nums,target);
        System.out.println(x);
    }
}
